package one.chapter_1.stack;

import java.util.Iterator;

public class LinkedStack<Item> implements Stack<Item> {

    private Node first;
    private int size;

    public Iterator<Item> iterator() {
        return new Iter();
    }

    public void push(Item item) {
        /**
         * 从头插入
         */
        Node node = new Node();
        node.item = item;

        Node oldFirst = first;
        node.next = oldFirst;
        first = node;

        size++;
    }

    /**
     * 从头取出
     *
     * @return
     */
    public Item pop() {
        if (isEmpty()) {
            return null;
        }
        size--;
        Node oldFirst = first;
        first = oldFirst.next;
        return oldFirst.item;
    }

    public boolean isEmpty() {
        return first == null;
    }

    public int size() {
        return size;
    }


    private class Node {
        Item item;
        Node next;
    }

    private class Iter implements Iterator<Item> {

        private int pos;
        private Node nextNode = first;

        public boolean hasNext() {
            return nextNode != null;
        }

        public Item next() {

            Item item = nextNode.item;
            nextNode = nextNode.next;
            return item;
        }

        public void remove() {

        }
    }

    public static void main(String[] args) {
        LinkedStack<Integer> stack = new LinkedStack<Integer>();

        stack.push(6);
        stack.push(5);
        stack.push(4);
        stack.push(3);
        stack.push(2);
        stack.push(1);
       /* Iterator<Integer> iterator = one.chapter_1.stack.iterator();
        while (iterator.hasNext()) {
            Integer val = iterator.next();
            System.out.println(val);
        }*/

        System.out.println(stack.pop());
        System.out.println(stack.pop());
        System.out.println(stack.pop());
        System.out.println(stack.pop());
        System.out.println(stack.pop());
        System.out.println(stack.pop());

    }
}
